package com.api.pay.util;

import cn.hutool.json.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.*;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import com.api.pay.config.ApiPayConfig;
import com.api.pay.model.domain.ApiOrder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.ArrayList;

@Component
@Slf4j
public class AliPayUtil {
    @Autowired
    private AlipayClient alipayClient;
    @Autowired
    private ApiPayConfig aliPayConfig;

    public String createTransaction(ApiOrder apiOrder) throws AlipayApiException {
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        setModel(apiOrder, request);
        request.setNotifyUrl("https://cn-jn-lt-plustmp1.natfrp.cloud:17688/api-pay/order/callback");
        //交易预下单请求
        AlipayTradePrecreateResponse response = alipayClient.certificateExecute(request);
        String shareCode = response.getQrCode();
        if (response.isSuccess()) {
            log.info("二维码：{}", shareCode);
        } else {
            log.error("支付宝预下单失败!!!,{}", response.getSubMsg());
            return null;
        }
        log.info("body:{}", response.getBody());
        return shareCode;
    }

    /**
     * 封装订单信息
     *
     * @param apiOrder
     * @param request
     */
    private static void setModel(ApiOrder apiOrder, AlipayTradePrecreateRequest request) {
        AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();
        model.setOutTradeNo(apiOrder.getSerialNumber());
        model.setTotalAmount(apiOrder.getTotalAmount().toString());
        model.setSubject(apiOrder.getSubject());
        GoodsDetail goodsDetail = new GoodsDetail();
        goodsDetail.setGoodsId(apiOrder.getGoodsId());
        goodsDetail.setGoodsName(apiOrder.getGoodsName());
        ArrayList<GoodsDetail> goodsDetails = new ArrayList<>();
        goodsDetails.add(goodsDetail);
        model.setGoodsDetail(goodsDetails);
        request.setBizModel(model);
    }

    /**
     * 支付宝支付成功回调通知验签
     *
     * @return true验签通过
     */
    public boolean rsaCheck(HttpServletRequest request) {
        // 获取支付宝POST过来反馈信息，对数据进行验签
        Map<String, String> params = new HashMap<>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }

        try {
            return AlipaySignature.rsaCheckV1(params, aliPayConfig.getPublicKey(), "UTF-8", aliPayConfig.getSignType());
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 查询订单
     *
     * @return
     * @throws AlipayApiException
     */
    public AlipayTradeQueryResponse queryOrder(ApiOrder apiOrder) throws AlipayApiException {
        // 构造请求参数以调用接口
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        AlipayTradeQueryModel model = new AlipayTradeQueryModel();
        setModel(apiOrder, request, model);
        AlipayTradeQueryResponse response = alipayClient.certificateExecute(request);
        if (response.isSuccess()) {
            return response;
        } else {
            throw new AlipayApiException(response.getSubMsg());
        }
    }

    private static void setModel(ApiOrder apiOrder, AlipayTradeQueryRequest request, AlipayTradeQueryModel model) {
        // 设置订单支付时传入的商户订单号
        model.setOutTradeNo(apiOrder.getSerialNumber());
        // 设置查询选项
        List<String> queryOptions = new ArrayList<>();
        //支付时间
        queryOptions.add("send_pay_date");
        //卖家实收金额
        queryOptions.add("receipt_amount");
        //买家实收金额
        queryOptions.add("buyer_pay_amount");
        model.setQueryOptions(queryOptions);
        request.setBizModel(model);
    }

    /**
     * 交易撤销
     * 如果用户已经支付就会退款然后取消,未支付交易会被取消
     *
     * @param apiOrder
     * @return
     * @throws AlipayApiException
     */
    public String cancalOrder(ApiOrder apiOrder) throws AlipayApiException {
        // 构造请求参数以调用接口
        AlipayTradeCancelRequest request = new AlipayTradeCancelRequest();
        AlipayTradeCancelModel model = new AlipayTradeCancelModel();
        // 设置原支付请求的商户订单号
        model.setOutTradeNo(apiOrder.getOrderSn());
        request.setBizModel(model);
        AlipayTradeCancelResponse response = alipayClient.certificateExecute(request);
        if (response.isSuccess()) {
            return response.getAction();
        } else {
            throw new AlipayApiException(response.getSubMsg());
        }
    }

    /**
     * 交易关闭接口
     * @param apiOrder
     * @return
     * @throws AlipayApiException
     */
    public boolean closeOrder(ApiOrder apiOrder) throws AlipayApiException {
        AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", apiOrder.getOrderSn());
        request.setBizContent(bizContent.toString());
        AlipayTradeCloseResponse response = alipayClient.certificateExecute(request);
        if (response.isSuccess()) {
            return true;
        } else {
            return false;
        }
    }

}
